package com.bbzn.device.client.service.emq.data;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bbzn.device.client.dataobject.Device;
import com.bbzn.device.client.dataobject.VcrInfo;
import com.bbzn.device.client.service.DeviceService;
import com.bbzn.device.client.service.EmqStrategy;
import com.bbzn.device.client.service.VcrInfoService;
import com.bbzn.device.client.utils.OptionalBean;
import com.bbzn.user.client.UserClient;
import com.bbzn.user.comment.User;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @Author: 蒋洪媛
 * @Date : 2021/11/25 17:26
 * @Version 1.0
 */
@Component
public class EmqVcrInfoStrategy implements EmqStrategy {

    @Resource
    private UserClient userClient;

    @Resource
    private DeviceService deviceService;

    @Resource
    private VcrInfoService vcrInfoService;

    // 上传本地录像文件信息
    @Override
    public String emqAction(String payLoad) {
        try {
            JSONObject jsonObject = JSON.parseObject(payLoad);
            String imei = jsonObject.getString("imei");
            if (!OptionalBean.ofNullable(imei).isPresent()) {
                return "json解析错误";
            }
            String bucketName = jsonObject.getString("bucketName");
            if (!OptionalBean.ofNullable(bucketName).isPresent()) {
                return "json解析错误";
            }
            String fileName = jsonObject.getString("fileName");
            if (!OptionalBean.ofNullable(fileName).isPresent()) {
                return "json解析错误";
            }
            Integer type = jsonObject.getInteger("type");
            if (null == type) {
                return "json解析错误";
            }
            VcrInfo vcrInfo = new VcrInfo();
            vcrInfo.setBucketName(bucketName);
            vcrInfo.setFileName(fileName);
            vcrInfo.setImei(imei);
            vcrInfo.setType(type);
            vcrInfo.setCreateTime(new Date());
            vcrInfo.setUpdateTime(new Date());

            Device dev = new Device();
            dev.setImei(imei);
            List<Device> deviceList = deviceService.findByAll(dev);
            if (CollectionUtils.isEmpty(deviceList)) {
                return "没有找到设备信息";
            }

            User user = userClient.selectByPrimaryKey(deviceList.get(0).getUserId());

            vcrInfo.setUserId(user.getId());
            vcrInfoService.insertSelective(vcrInfo);
        } catch (Exception e) {
            return "上传本地录像文件信息失败！";
        }
        return "上传本地录像文件信息成功！";
    }
}
